package com.zhongfl.crm.service.impl.boss;

import com.zhongfl.crm.enums.boss.MessageSendMethod;
import com.zhongfl.crm.enums.boss.MessageSendType;
import com.zhongfl.crm.exception.CRMException;
import com.zhongfl.crm.lixiao.mapper.MessageSendTaskMapper;
import com.zhongfl.crm.model.boss.MessageSendTask;
import com.zhongfl.crm.service.boss.MessageSendTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import tech.heptagram.channel.api.common.AssertUtils;
import tech.heptagram.core.common.util.JsonUtil;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 消息发送服务
 *
 * @author wang.yuchuan
 * @date 2018/7/23
 */
@Service
@Slf4j
public class MessageSendTaskServiceImpl implements MessageSendTaskService {

    @Resource
    private MessageSendTaskMapper messageSendTaskMapper;

    /**
     * 保存消息发送任务
     *
     * @param messageSendTask
     */
    @Override
    public void save(MessageSendTask messageSendTask) {
        AssertUtils.notNull(messageSendTask, "消息发送任务不能为Null");
        AssertUtils.hasText(messageSendTask.getMsgKey(), "消息Key不能为空");
        AssertUtils.hasText(messageSendTask.getTopic(), "消息topic不能为空");

        messageSendTaskMapper.insert(messageSendTask);
    }

    @Override
    public void save(MessageSendType msgType, String relationNo, String msgKey, String topic, String content) {
        MessageSendTask sendTask = new MessageSendTask();
        sendTask.setMsgType(msgType);
        sendTask.setContent(content);
        sendTask.setCreatedBy("System");
        sendTask.setMsgKey(msgKey);
        sendTask.setRelationNo(relationNo);
        sendTask.setTopic(topic);
        sendTask.setSendMethod(MessageSendMethod.QI_YE_WECHAT);

        save(sendTask);
    }

    @Override
    public void save(MessageSendType msgType, String relationNo, String msgKey, String topic, Object content) {
        String strContent = "";
        if (Objects.nonNull(content)) {
            try {
                strContent = JsonUtil.toJson(content);
            } catch (CRMException e) {
                log.error("消息保存转json错误:", e);
            }
        }
        save(msgType, relationNo, msgKey, topic, strContent);
    }
}
